{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11.2\n",
      "23.2\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "X = np.array([[6], [8], [10], [14], [18]]).reshape(-1, 1)\n",
    "x_bar = X.mean()\n",
    "print(x_bar)\n",
    "\n",
    "# Note that we subtract one from the number of training instances when calculating the sample variance. \n",
    "# This technique is called Bessel's correction. It corrects the bias in the estimation of the population variance\n",
    "# from a sample.\n",
    "variance = ((X - x_bar)**2).sum() / (X.shape[0] - 1)\n",
    "print(variance)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "23.2\n"
     ]
    }
   ],
   "source": [
    "print(np.var(X, ddof=1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "22.65\n",
      "22.65\n"
     ]
    }
   ],
   "source": [
    "# We previously used a List to represent y.\n",
    "# Here we switch to a NumPy ndarray, which provides a method to calulcate the sample mean.\n",
    "y = np.array([7, 9, 13, 17.5, 18])\n",
    "\n",
    "y_bar = y.mean()\n",
    "# We transpose X because both operands must be row vectors\n",
    "covariance = np.multiply((X - x_bar).transpose(), y - y_bar).sum() / (X.shape[0] - 1)\n",
    "print(covariance)\n",
    "print(np.cov(X.transpose(), y)[0][1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
